﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Common.Helper
{
    public static class MD5Helper
    {
        /// <summary>
        /// MD5加密字符串处理
        /// </summary>
        /// <param name="half">加密是16位还是32位；如果为true为16位</param>
        /// <param name="input">待加密码字符串</param>
        /// <returns></returns>
        public static string ToMd5(this string input, bool half = false)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                var strResult = BitConverter.ToString(result);
                strResult = strResult.Replace("-", "");
                if (half)//16位MD5加密（取32位加密的9~25字符）
                {
                    strResult = strResult?.Substring(8, 16);
                }
                return strResult;
            }
        }
        /// <summary>
        /// 生成每天随机数
        /// </summary>
        /// <returns></returns>
        public static string NewRandom()
        {
            byte[] randomBytes = new byte[4];
            RNGCryptoServiceProvider rngServiceProvider = new RNGCryptoServiceProvider();
            rngServiceProvider.GetBytes(randomBytes);
            Int32 result = BitConverter.ToInt32(randomBytes, 0);
            string strDate = DateTime.Now.ToString("yyMMdd");
            return strDate + Math.Abs(result);
        }

    }
}
